import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import store from './store'
import { asyncRoutes } from '@/router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // 白名单

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  // 如果有token 判断是否访问路径为/login 如果是 则跳转到首页 如果不是 则看是否在白名单内
  if (hasToken) {
    if (to.path === '/login') {
      // 跳转到主页
      next('/')
      NProgress.done()
    } else {
      // 判断是否获取过资料
      if (!store.getters.name) {
        const { permissions } = await store.dispatch("user/getUserInfo")
        const permissionList = []
        permissions.forEach(element => {
          permissionList.push(element.permissionName)
        });
        const filterRouter = asyncRoutes.filter(item => {
          return permissionList.includes(item.name)
        })
        // 筛选后的路由
        store.commit("user/setRoutes", filterRouter)
        router.addRoutes([...filterRouter, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
// 路由后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
